﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Universe.WCF.Behaviors;

namespace Universe.WCF.Behaviors
{
    class TransparentDeliveryInspector : IDispatchMessageInspector, IClientMessageInspector
    {
        private TransparentDeliveryConfiguration _configuration;

        public TransparentDeliveryInspector(TransparentDeliveryConfiguration configuration)
        {
            _configuration = configuration;
        }

        public static readonly string HeaderNamespace = "universe.wcf.transparentdelivery.dictionary";

        object IDispatchMessageInspector.AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
            DeliveryDictionary dd = new DeliveryDictionary(headers);
            _configuration.OnServer(request.Headers.Action, dd);
            return null;
        }

        void IDispatchMessageInspector.BeforeSendReply(ref Message reply, object correlationState)
        {
        }

        object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            DeliveryDictionary data = new DeliveryDictionary(request.Headers);
            _configuration.OnClient(request.Headers.Action, data);
            return null;
        }

        void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState)
        {
        }
    }
}